/**
 * @Author:Geln Yang
 * @Created:2008-8-13
 * $ Revision: 1.0 $
 * $ Author: Geln Yang $
 * $ Date: 2008-8-13 $
 */
package org.geln.web.db;

import java.io.File;
import java.sql.DriverManager;

import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.dbunit.operation.DatabaseOperation;

/**
 * @Author:Geln Yang
 * @Created:2008-8-13
 */
public class SetupDemoData {
	/**
	 * 
	 * @param args driverclass,url,user,password,xmlfile
	 * @throws Exception
	 */
	public static void main(String args[]) throws Exception {
		for(int i=0;i<args.length;i++){
			System.out.println(i+":"+args[i]);
		}
		if(args == null || args.length<5){
			throw new IllegalArgumentException("invalidate parameter:driverclass,url,user,password,xmlfile!");
		}
		String driverClass = args[0];
		
		if(driverClass == null || driverClass.trim().length() == 0){
			throw new IllegalArgumentException("driverClass parameter missing!");
		}
		
		String url = args[1];
		
		if(url == null || url.trim().length() == 0){
			throw new IllegalArgumentException("url parameter missing!");
		}
		
		Class.forName(driverClass);
		
		String user = args[2];
		String password = args[3];
		
		String resource = args[4];
		
		String schema = null;
		if(args.length>5){
			schema = args[5];
		}
		IDatabaseConnection connection = null;
		try {
			if(schema !=null && schema.trim().length()>0)
				connection = new DatabaseConnection(DriverManager.getConnection(url, user, password),schema);
			else
				connection = new DatabaseConnection(DriverManager.getConnection(url, user, password));
			File dataFile = new File(resource);
			if(!dataFile.exists() || !dataFile.isFile()){
				throw new IllegalArgumentException("invalidate dataset file.");
			}
			IDataSet dataSet = new FlatXmlDataSet(dataFile);
			DatabaseOperation.CLEAN_INSERT.execute(connection, dataSet);
		} finally{
			if(connection != null){
				connection.close();
			}
		}
	}
}

